/*
 * Log.java
 *
 * Created on July 30, 2006, 5:08 PM
 *
 * @author Francois Daniels
 */

package za.gateway.io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.StringTokenizer;

/** 
 * This class will be used to track down bugs which exists in the 
 * system. Each time we catch an exception we should log it with this 
 * class. This way if the system is behaving funny we can come back in 
 * a few days and examine the logs.
 *
 * @author Francois Daniels
 */
public abstract class Log {
    
    /**
     * This function will take the exception and write it to the 
     * Exceptions.log file. This file is situated in the root directory 
     * of the application.
     *
     * @param exception the exception which we expect to log.
     **/
    public static void ERROR (Exception exception) {
        try {
            //exception.printStackTrace ();
            
            BufferedWriter file = new BufferedWriter (new FileWriter 
                    (urlToFile (ClassLoader.getSystemResource 
                        ("Exceptions.log").getFile ())));
            
            file.write (exceptionToString (exception.getStackTrace (),
                    exception.getMessage ()));
            file.close ();
        } catch (Exception e)
        {}
    }
    
    /**
     * This function converts a URL to a file name.
     *
     * @param _url  The URL we wish to convert to a file name.
     * @return      The file name corresponding to _url.
     **/
    private static String urlToFile (String _url) {
        String url = _url.substring (1);
        StringTokenizer st = new StringTokenizer (url, "%");
        String file = new String ();
        
        if (st.hasMoreTokens ())
            file += st.nextToken () + " ";
        
        while (st.hasMoreTokens ())
            file += st.nextToken ().substring (2) + " ";
        
        file = file.trim ();
        return file;
    }
    
    /**
     * This function takes an array of objects and converts them to a 
     * String. The msg is the first line of the String. Each object 
     * will be seperated by a "\r\n".
     *
     * @param objects   An array of objects we which to convert to a 
     *                  String.
     * @param msg       The message to display at the start of the 
     *                  String.
     * @return          A concatentated String consisting of the msg, 
     *                  and object array.
     **/
    private static String exceptionToString (Object [] objects, 
            String msg) {
        
        if (objects == null) return msg;
        
        String description = msg +"\r\n";
        for (int i = 0; i < objects.length; i++)
            description += objects[i].toString () +"\r\n";
        
        description += "\r\n\r\n";
        return description;
    }
}
